const fs = require('fs')
const path = require('path')
const {doExcel, toUpperCaseByStr} = require("./parseExcel");
const {genServerClass, genClassMap, genBaseClass, genClientBaseClass, genClientClassMap, genClientClass} = require("./genJs");
const {upperCaseFirstLatter} = require("./common");

// 生成json 配置
function genJson(clientOrServerRow, outJsonDir, excelDir) {
    if (fs.existsSync(outJsonDir)) {
        console.log('删除json文件')
        fs.rmSync(outJsonDir, {recursive: true})
    } else {
        // 不存在目录，新建
        fs.mkdirSync(outJsonDir, {recursive: true})
    }
    // 表格列表 example: ["iconopen","mainTask"]
    const excelFiles = [];
    // 表名 +分表名
    const excelFen = [];
    // 表格与表单的数据类型 example:{iconopen:{id:string}}
    const excelAndSheets = {};

    // 解析表格
    fs.readdirSync(excelDir).forEach((excelName) => {
        // 查找 excel
        const extName = path.extname(excelName)
        if ((extName === '.xls' || extName === '.xlsx') && !excelName.startsWith('~')) {
            excelFiles.push(excelName.split('_')[0]);
            doExcel(excelName, excelFen, excelAndSheets, clientOrServerRow, excelDir, outJsonDir);
        }
    });
    return {excelFiles, excelFen, excelAndSheets}
}

// 生成 model
function genModel(excelAndSheets, tableDir, modelDir, jsonDir) {
    // 生成 配置model
    const keys = Object.keys(excelAndSheets).sort((a, b) => a.localeCompare(b))
    const classMaps = {}
    let text = ''
    for (const name of keys) {
        // excel 表
        const excel = excelAndSheets[name]
        // 所有子表
        const subTables = Object.keys(excel).sort((a, b) => a.localeCompare(b))
        for (const subTable of subTables) {
            // 配置表名
            const jsonTableName = `${name}${toUpperCaseByStr(subTable)}`
            const fields = excel[subTable]
            const fieldKeys = Object.keys(fields).sort((a, b) => a.localeCompare(b))
            // 生成 interface
            text = `export interface IJson${toUpperCaseByStr(jsonTableName)} {\n`
            for (const field of fieldKeys) {
                // 所有字段
                const info = fields[field]
                if (info.isKey !== 0) {
                    console.info(`find key not 0, ${jsonTableName}`)
                }
                text += `\t// ${info.ps.replace(/\s/g, '')}\n\t${info.keys}: ${info.value}\n`
            }
            text += '}\n'
            // 写入文件
            // console.log(text)
            fs.writeFileSync(path.join(tableDir, jsonTableName + '.ts'), text)
            // 生成 class 类
            text = genServerClass(jsonTableName, jsonDir)
            if (!fs.existsSync(path.join(modelDir, jsonTableName + '.ts'))) {
                // 检查 model 不存在，生成新 model
                fs.writeFileSync(path.join(modelDir, jsonTableName + '.ts'), text)
            }
            classMaps[jsonTableName] = `Json${upperCaseFirstLatter(jsonTableName)}`
        }
    }

    // 生成 jsonBase
    fs.writeFileSync(`${path.join(modelDir, 'jsonBase.ts')}`, genBaseClass())
    // 生成 index
    const classIndex = genClassMap(classMaps)
    fs.writeFileSync(`${path.join(modelDir, 'index.ts')}`, classIndex)
}

// 生成客户端 model
function genClientModel(excelAndSheets, tableDir, modelDir, jsonDir) {
    // 生成 配置model
    const keys = Object.keys(excelAndSheets).sort((a, b) => a.localeCompare(b))
    const classMaps = {}
    let text = ''
    for (const name of keys) {
        // excel 表
        const excel = excelAndSheets[name]
        // 所有子表
        const subTables = Object.keys(excel).sort((a, b) => a.localeCompare(b))
        for (const subTable of subTables) {
            // 配置表名
            const jsonTableName = `${name}${toUpperCaseByStr(subTable)}`
            const fields = excel[subTable]
            const fieldKeys = Object.keys(fields).sort((a, b) => a.localeCompare(b))
            // 生成 interface
            text = `export interface IJson${toUpperCaseByStr(jsonTableName)} {\n`
            for (const field of fieldKeys) {
                // 所有字段
                const info = fields[field]
                if (info.isKey !== 0) {
                    console.info(`find key not 0, ${jsonTableName}`)
                }
                text += `\t// ${info.ps.replace(/\s/g, '')}\n\t${info.keys}: ${info.value}\n`
            }
            text += '}\n'
            // 写入文件
            // console.log(text)
            fs.writeFileSync(path.join(tableDir, jsonTableName + 'Tbl.ts'), text)
            // 生成 class 类
            text = genClientClass(jsonTableName, jsonDir)
            if (!fs.existsSync(path.join(modelDir, jsonTableName + 'Model.ts'))) {
                // 检查 model 不存在，生成新 model
                fs.writeFileSync(path.join(modelDir, jsonTableName + 'Model.ts'), text)
            }
            classMaps[jsonTableName] = `Json${upperCaseFirstLatter(jsonTableName)}`
        }
    }

    // 生成 jsonBase
    fs.writeFileSync(`${path.join(modelDir, 'jsonBase.ts')}`, genClientBaseClass())
    // 生成 index
    const classIndex = genClientClassMap(classMaps)
    fs.writeFileSync(`${path.join(modelDir, 'indexJsonTable.ts')}`, classIndex)
}


module.exports = {
    genJson,
    genModel,
    genClientModel,
}
